#include<iostream>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<cstdlib>

using namespace std;

#define N 2
#define NUM 1024


void Writer(int wfd)
{
    string s = "i am child";
    pid_t self = getpid();
    int number = 0;
    char buffer[NUM];
    while(1)
    {
        buffer[0] = 0;
        snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number++);
        write(wfd,buffer,strlen(buffer));
        sleep(1);
    }
}

void Reader(int rfd)
{
    char buffer[NUM];
    while(1)
    {
         ssize_t n = read(rfd,buffer,sizeof(buffer));
         if(n > 0)
        {
            buffer[n] = 0;

            cout<<"father get a msg["<<getpid()<<"]"<<buffer<<endl;
        }

    
    }
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n < 0)
    {
        return 1 ;
    }
    pid_t id = fork();
    if(n < 0)
    {
        return 2;
    }
    if(id == 0)
    {
        close(pipefd[0]);
        Writer(pipefd[1]);


        close(pipefd[1]);
        exit(0);

    }

    close(pipefd[1]);
    Reader(pipefd[0]);

    pid_t rid = waitpid(pipe[fd0],nullptr,0);

    close(pipefd[0]);



    return 0;
}
